package com.tdx.blog_nowcoder.controller;

import com.tdx.blog_nowcoder.constant.CommentReplyConstant;
import com.tdx.blog_nowcoder.entity.Comment;
import com.tdx.blog_nowcoder.entity.DiscussPort;
import com.tdx.blog_nowcoder.entity.MyEvent;
import com.tdx.blog_nowcoder.entity.User;
import com.tdx.blog_nowcoder.utils.RedisKeyUtils;
import com.tdx.blog_nowcoder.utils.event.EventProducer;
import com.tdx.blog_nowcoder.service.CommentService;
import com.tdx.blog_nowcoder.service.DiscussPortService;
import com.tdx.blog_nowcoder.service.LikeService;
import com.tdx.blog_nowcoder.service.UserService;
import com.tdx.blog_nowcoder.utils.DumpJSONToString;
import com.tdx.blog_nowcoder.utils.Page;
import com.tdx.blog_nowcoder.utils.ThreadHostHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

import static com.tdx.blog_nowcoder.constant.CommentReplyConstant.ENTITY_TYPE_COMMENT;
import static com.tdx.blog_nowcoder.constant.DiscusspostConstant.*;
import static com.tdx.blog_nowcoder.constant.KafkaTopicConstant.TOPIC_DELETE;
import static com.tdx.blog_nowcoder.constant.KafkaTopicConstant.TOPIC_PUBLISH;

@Controller
@RequestMapping("/discuss")
public class DiscussPortController {
    private static final Logger logger = LoggerFactory.getLogger(DiscussPortController.class);
    @Autowired
    private ThreadHostHolder threadHostHolder;

    @Autowired
    private UserService userService;
    @Autowired
    private CommentService commentService;

    @Autowired
    private DiscussPortService discussPortService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(path = "/add",method = RequestMethod.POST)
    @ResponseBody
    public String adddiscuss_port(String title,String content){

        User user = threadHostHolder.getUser();
        if(user==null){
           return DumpJSONToString.getJsonString(403,"未登入！");
        }
        DiscussPort discussPort = new DiscussPort();
        discussPort.setUserId(user.getId());
        discussPort.setTitle(title);
        discussPort.setContent(content);
        discussPort.setCreateTime(new Date());

        int row = discussPortService.addDiscussPort(discussPort);
        System.out.println(row);
//        if(row!=)

        // 计算帖子分数
        String redisKey = RedisKeyUtils.getPostScoreKey();
        redisTemplate.opsForSet().add(redisKey, discussPort.getId());

        return DumpJSONToString.getJsonString(200,"发布成功！");
    }

    @RequestMapping(path = "/detail/{discussPostId}",method = RequestMethod.GET)
    public String getDetailPage(@PathVariable("discussPostId") int discussPostId, Model model, Page page){

        // 帖子的信息
        DiscussPort port = discussPortService.getDiscussPostsById(discussPostId);
        if(port==null){
            logger.error("帖子信息异常!");
            return "site/error/500";
        }
        model.addAttribute("post", port);

        //获取帖子的用户信息
        User user = userService.selectUserById(port.getUserId());

        model.addAttribute("user", user);

        // 帖子实体类型 点赞数量
        long disport_likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, discussPostId);
        model.addAttribute("disport_likeCount", disport_likeCount);

        // 点赞状态
        int likeStatus = threadHostHolder.getUser() == null ? 0 :
                likeService.findEntityLikeStatus(threadHostHolder.getUser().getId(),
                        ENTITY_TYPE_COMMENT, discussPostId);

        model.addAttribute("likeStatus", likeStatus);

        // 评论分页信息
        page.setPerPageSize(5);
        page.setPath("/discuss/detail/" + discussPostId);
        page.setTotalPageNums(port.getCommentCount());


        // 评论: 给帖子的评论
        // 回复: 给评论的评论
        // 评论列表

        //帖子

        List<Comment> commentList = commentService.selectCommentsByEntity(ENTITY_TYPE_COMMENT,
                port.getId(),
                page.getOffset(),page.getPerPageSize());
        System.out.println("size is");
        System.out.println(commentList.size());
        List<Map<String,Object>> commentVoList = new ArrayList<>();
        if(commentList!=null){
            for(Comment comment:commentList){
                Map<String,Object> commentVo = new HashMap<>();
                commentVo.put("comment",comment);
                commentVo.put("user",userService.selectUserById(comment.getUserId()));
                System.out.println(userService.selectUserById(comment.getUserId()).getHeaderUrl());
                // 点赞数量
                long comment_likeCount = likeService.findEntityLikeCount(CommentReplyConstant.ENTITY_TYPE_REPLY, comment.getId());
                commentVo.put("comment_likeCount", comment_likeCount);
                // 点赞状态
                likeStatus = threadHostHolder.getUser() == null ? 0 :
                        likeService.findEntityLikeStatus(threadHostHolder.getUser().getId(), CommentReplyConstant.ENTITY_TYPE_REPLY,
                                comment.getId());
                commentVo.put("likeStatus", likeStatus);


                // 回复列表
                List<Comment> replyList = commentService.selectCommentsByEntity(CommentReplyConstant.ENTITY_TYPE_REPLY,
                        comment.getId(),
                        0,Integer.MAX_VALUE);
                List<Map<String,Object>> replyVoList = new ArrayList<>();
                if(replyList!=null){
                    Map<String, Object> replyVo = new HashMap<>();
                    for(Comment reply:replyList){
                        replyVo.put("reply",reply);
                        // 作者
                        replyVo.put("user", userService.selectUserById(reply.getUserId()));

                        //回复给谁
                        // 回复目标 0表示没有 否则有其回复的用户对象
                        User target = reply.getTargetId() == 0 ? null : userService.selectUserById(reply.getTargetId());
                        replyVo.put("target", target);

                        // 点赞数量
                        long reply_likeCount = likeService.findEntityLikeCount(CommentReplyConstant.ENTITY_TYPE_REPLY, reply.getId());
                        replyVo.put("reply_likeCount", reply_likeCount);
                        // 点赞状态
                        likeStatus = threadHostHolder.getUser() == null ? 0 :
                                likeService.findEntityLikeStatus(threadHostHolder.getUser().getId(),
                                        CommentReplyConstant.ENTITY_TYPE_REPLY, reply.getId());
                        replyVo.put("likeStatus", likeStatus);

                        replyVoList.add(replyVo);
                    }
                }

                commentVo.put("replylist",replyVoList);

                //回复数量

                // 回复数量
                int replyCount = commentService.selectCountByEntity(CommentReplyConstant.ENTITY_TYPE_REPLY, comment.getId());
                commentVo.put("replyCount", replyCount);

                commentVoList.add(commentVo);

            }
        }

        for(Map<String,Object> map:commentVoList){
            Comment comment = (Comment) map.get("comment");
            System.out.println("helll");
            System.out.println(comment==null);
        }


        model.addAttribute("comments", commentVoList);
        model.addAttribute("comments_size",commentVoList.size());
//        return "site/discuss-detail";
        return "site/post2";
    }


    @RequestMapping(path = "/top",method = RequestMethod.POST)
    @ResponseBody
    public String setDisPostTop(int postId){
        discussPortService.updateType(postId,DIS_TOP); // 置顶
        //
        // 触发发帖事件
        MyEvent event = new MyEvent()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(threadHostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_COMMENT)
                .setEntityId(postId);

        eventProducer.fireEvent(event);



        return DumpJSONToString.getJsonString(200,"置顶成功!");

    }

    // 加精
    @RequestMapping(path = "/wonderful", method = RequestMethod.POST)
    @ResponseBody
    public String setWonderful(int postId) {
        discussPortService.updateStatus(postId, DIS_WONDERFUL);

        // 触发发帖事件
        MyEvent event = new MyEvent()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(threadHostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_COMMENT)
                .setEntityId(postId);

        eventProducer.fireEvent(event);

//        // 计算帖子分数
//        String redisKey = .getPostScoreKey();
//        redisTemplate.opsForSet().add(redisKey, id);

        // 计算帖子分数
        String redisKey = RedisKeyUtils.getPostScoreKey();
        redisTemplate.opsForSet().add(redisKey, postId);

        return  DumpJSONToString.getJsonString(200,"加精成功!");
    }

    // 删除
    @RequestMapping(path = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public String setDelete(int postId) {
        discussPortService.updateStatus(postId, DIS_DELETE);

        // 触发删帖事件
        MyEvent event = new MyEvent()
                .setTopic(TOPIC_DELETE)
                .setUserId(threadHostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_COMMENT)
                .setEntityId(postId);
        eventProducer.fireEvent(event);

        return DumpJSONToString.getJsonString(200,"删帖成功!");
    }


}
